from fastapi import APIRouter, Query, Depends
from pymongo.database import Database
from typing import Optional
from dependencies import get_es, get_mongo_db_of_condition_safety
from elasticsearch import AsyncElasticsearch
from config import es_conf
from schema.resp import RestfulModel, PageInfo
from service import vehicle_log_permutation_service as vlog_service
from .condition_safety_settings_controller import SettingsName


vehicle_log_perception_router = APIRouter(prefix='/condition_safety/log-permutation',
                                          tags=['车辆状态安全-安全日志/监控日志数据'])


@vehicle_log_perception_router.get('/sec-log',
                                   summary='查看安全日志信息',
                                   response_model=RestfulModel[PageInfo])
async def get_security_logs(page_num: Optional[int] = Query(1, title='页号', alias='pageNum'),
                            page_size: Optional[int] = Query(50, title='一页多少数据', alias='pageSize'),
                            mongo_db: Database = Depends(get_mongo_db_of_condition_safety),
                            es_client: AsyncElasticsearch = Depends(get_es)):
    # 从 MongoDB 读取出配置信息，即所要查询的日期
    setting_doc = mongo_db['settings'].find_one({'name': SettingsName.SECURITY_LOG})
    when = setting_doc['data']['when']
    when = vlog_service.covert_when_from_special_format(when)
    # 对 ES 进行查询，ES 中 index 不存在时会抛出异常交给全局处理器来处理
    es_index = es_conf.SECURITY_LOG_INDEX_PREFIX + when
    es_resp = await vlog_service.simple_query_es_by_pagination(es_client, es_index, page_size, page_num)
    return RestfulModel.success(PageInfo(
        total=es_resp['hits']['total']['value'],
        list=es_resp['hits']['hits']
    ))


@vehicle_log_perception_router.get('/os-log',
                                   summary='查看告警日志信息',
                                   response_model=RestfulModel[PageInfo])
async def get_security_logs(page_num: Optional[int] = Query(1, title='页号', alias='pageNum'),
                            page_size: Optional[int] = Query(50, title='一页多少数据', alias='pageSize'),
                            mongo_db: Database = Depends(get_mongo_db_of_condition_safety),
                            es_client: AsyncElasticsearch = Depends(get_es)):
    setting_doc = mongo_db['settings'].find_one({'name': SettingsName.SECURITY_LOG})
    when = setting_doc['data']['when']
    when = vlog_service.covert_when_from_special_format(when)
    es_index = es_conf.OS_LOG_INDEX_PREFIX + when
    es_resp = await vlog_service.simple_query_es_by_pagination(es_client, es_index, page_size, page_num)
    return RestfulModel.success(PageInfo(
        total=es_resp['hits']['total']['value'],
        list=es_resp['hits']['hits']
    ))
